package com.jiuxian.example.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    public static Map<String, Channel> channels = new HashMap<>();

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 连接建立
     * 此时将当前channel加入到ctx
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 把用户加入聊天的信息推送给其他客户端
        // 遍历所有channel并发送
        channelGroup.writeAndFlush(sdf.format(new Date()) + "  " + "[客户端]" + channel.remoteAddress() + " 加入聊天");
        channelGroup.add(channel);
        System.out.println("channelGroup-size: " + channelGroup.size());

        channels.put(channel.remoteAddress().toString(), channel);
    }

    /**
     * channel处于活动状态
     * 提示xx上线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date()) + "  " + ctx.channel().remoteAddress() + "上线...");
    }

    /**
     * channel处于非活动状态
     * 提示xx离线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date()) + "  " + ctx.channel().remoteAddress() + "离线...");
    }

    /**
     * 断开连接
     * 推送xx离开给所有在线用户
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 断开连接时会自动从channelGroup中剔除
//        channelGroup.remove(channel);
        channelGroup.writeAndFlush(sdf.format(new Date()) + "  " + "[客户端]" + channel.remoteAddress() + " 离开...");
        System.out.println("channelGroup-size: " + channelGroup.size());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        // 遍历channelGroup, 根据不同channel发送不同消息
        channelGroup.forEach(ch -> {
            if (channel != ch) {
                // 在别的用户展示
                ch.writeAndFlush(sdf.format(new Date()) + "  " + "[用户]" + channel.remoteAddress() + " 发送了消息: " + msg + "\n");
            } else {
                // 自己展示
                ch.writeAndFlush(sdf.format(new Date()) + "  " + "[自己]发送了消息: " + msg + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
